import { onBeforeMount, onBeforeUnmount, onMounted, ref } from "vue";

// 默认适配的宽高
export const width = 1920;
export const height = 1080;

type ResizeType = {
    w?: number;
    h?: number;
    fullScreen?: boolean;
    delay?:number;
}

export const useResize = (options: ResizeType = {}) => {
    const { w = width, h = height, fullScreen = false, delay = 100 } = options;

    const screenRef = ref();
    const scale = ref(1);

    function resize() {
        // 获取浏览器的高度
        const clientWidth = document.body.clientWidth;
        const clientHeight = document.body.clientHeight;

        // 计算比例缩放
        const scaleW = clientWidth / w;
        const scaleH = clientHeight / h;
        scale.value = Math.min(scaleW, scaleH); // 保持内容完整且比例不变

        if(fullScreen) {
            screenRef.value.style.transform = `scale(${scaleW}, ${scaleH})`;
        }else {
            screenRef.value.style.transform = `scale(${scale.value})`;
            // 设置居中
            screenRef.value.style.left = `${(clientWidth - w * scale.value) / 2}px`;
            screenRef.value.style.top = `${(clientHeight - h * scale.value) / 2}px`;
        }
    }

    const resizeDelay = debounce(resize, delay);

    onMounted(()=> {
        if(screenRef.value) {
            resize();
            window.addEventListener('resize', resizeDelay);
        }
    });

    onBeforeUnmount(()=> {
        window.removeEventListener('resize', resizeDelay);
    });

    return {
        screenRef,
        scale
    }
}

/**
 * 防抖
 */
function debounce(fn: Function, delay: number) {
    let timer:NodeJS.Timeout;
    return function(...args: any[]) {
        if(timer) clearTimeout(timer);
        timer = setTimeout(()=> {
            typeof fn === 'function' && fn.apply(null, args);
            clearTimeout(timer);
        }, delay > 0 ? delay : 100);
    }
}